package day2.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebFilter( value = "/day2/filter/*" ,initParams = {@WebInitParam(name = "encode",value = "utf-8")})
public class MyFilter implements Filter {
    FilterConfig cfg;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("init方法被执行。。。");
        this.cfg=filterConfig;
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        String encode=cfg.getInitParameter("encode");
        System.out.println("设置的编码为："+encode);
        req.setCharacterEncoding(encode);
        resp.setContentType("text/html;charset="+encode);
        HttpServletRequest r= (HttpServletRequest) req;
        String name= (String) ((HttpServletRequest) req).getSession().getAttribute("name");
        if(name!=null){
            chain.doFilter(req,resp);
        }else {
            //((HttpServletResponse)resp).sendRedirect("/day2/filter/login.jsp");
            r.getRequestDispatcher("/day2/filter/login.jsp").forward(r,resp);
        }
    }

    @Override
    public void destroy() {
        System.out.println("destroy方法执行了。。。");
    }
}
